package com.sun.androidexerciseproject.function.phone;

import android.Manifest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;

import com.android.internal.telephony.ITelephony;
import com.sun.androidexerciseproject.function.R;
import com.sun.androidexerciseproject.function.logreport.util.LogUtil;

import java.lang.reflect.Method;

public class PhoneActivity extends AppCompatActivity implements View.OnClickListener {
    private ITelephony mTelephonyService;
    /**
     * sendMsg
     */
    private Button mIdSendMsg;
    /**
     * startRunable
     */
    private Button mIdStartRunable;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            String content = (String) msg.obj;
            LogUtil.d("mHandler content " + content + " what " + what);
            mHandler.removeCallbacksAndMessages(null);
        }
    };
    /**
     * cancelRunable
     */
    private Button mIdCancelRunable;

    private TestReceiver mTestReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone);
        initView();
        getMemory();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show());
        initTel();
        checkPermission();
        initReceiver();
//        startOtherActivity();
    }

    private void checkPermission() {
        int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.MODIFY_PHONE_STATE}, 0);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void initTel() {
        try {
            TelephonyManager telephony = (TelephonyManager) getApplication()
                    .getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
            Class<?> c = Class.forName(telephony.getClass().getName());

            Method m = c.getDeclaredMethod("getITelephony");
            m.setAccessible(true);

            mTelephonyService = (ITelephony) m.invoke(telephony);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mIdSendMsg = (Button) findViewById(R.id.id_send_msg);
        mIdSendMsg.setOnClickListener(this);
        mIdStartRunable = (Button) findViewById(R.id.id_start_runable);
        mIdStartRunable.setOnClickListener(this);
        mIdCancelRunable = (Button) findViewById(R.id.id_cancel_runable);
        mIdCancelRunable.setOnClickListener(this);
    }

    private void getMemory() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        int size = manager.getMemoryClass();
        LogUtil.d("getMemory size " + size);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.id_send_msg:
                sendMsg();
                break;
            case R.id.id_start_runable:
                startRunable();
                break;
            case R.id.id_cancel_runable:
                cancelRunable();
                break;
        }
    }

    private void cancelRunable() {
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void sendMsg() {
        Message message = Message.obtain();
        message.what = 1;
        message.obj = "testMessage";
        mHandler.sendMessage(message);
    }

    private void startRunable() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LogUtil.d("startRunable");
            }
        }, 5000);
    }

    private void startOtherActivity() {
        Uri uri = Uri.parse("test://123/travel/oversea?id=1000");
        Intent intent = new Intent(null, uri);
        startActivity(intent);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    private void initReceiver() {
        mTestReceiver = new TestReceiver();
        IntentFilter intentFilter = new IntentFilter("com.jtpay.unionpay.ACTION_TEST");
        registerReceiver(mTestReceiver, intentFilter);
    }

    class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    if (mTelephonyService != null) {
                        try {
                            mTelephonyService.answerRingingCall();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }

    class TestReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.d("TestReceiver onReceive action " + intent.getAction());
        }
    }
}